package com.qst.survey.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qst.survey.entity.Question;
import com.qst.survey.entity.User;
import com.qst.survey.entity.UserReply;
import com.qst.survey.mapper.QuestionMapper;
import com.qst.survey.mapper.UserMapper;
import com.qst.survey.mapper.UserReplyMapper;
import com.qst.survey.service.UserService;
import com.qst.survey.util.GetCode;
import com.qst.survey.util.MailUtil;
import com.qst.survey.util.RedisUtils;
import com.qst.survey.vo.VM;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Date: 2021/3/19 21:36
 * @Description: 用户具体服务类
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserReplyMapper userReplyMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    MailUtil mailUtil;

    /**
     * @param user ：用户类
     * @return com.qst.survey.entity.User
     * @description TODO  用户登录方法
     * @date 2021/4/2
     */
    @Transactional
    @Override
    public User loginUser(User user) {
        //根具登录名字获取管理员信息
        //查询数据库
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", user.getUsername());
        User userResult = userMapper.selectOne(queryWrapper);
        //对密码进行校验
        if (userResult == null) {
            return null;
        }
        boolean checkpw = BCrypt.checkpw(user.getPassword(), userResult.getPassword());
        if (checkpw) {
            return userResult;
        } else {
            return null;
        }
        //返回结果
    }

    /**
     * @param username ：用户名
     * @return com.qst.survey.entity.User
     * @description TODO   通过用户名来查出一个用户
     * @date 2021/4/2
     */
    @Override
    @Transactional
    public User findOne(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }

    /**
     * @param user ：用户
     * @return boolean
     * @description TODO 增加一个用户
     * @date 2021/4/2
     */
    @Transactional
    @Override
    public boolean addUser(User user) {
        //获取盐
        String gensalt = BCrypt.gensalt();
        //对用户密码加密
        String hashpw = BCrypt.hashpw(user.getPassword(), gensalt);
        user.setPassword(hashpw);
        //保存到数据库
        int insert = userMapper.insert(user);
        if (insert > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param user 用户
     * @return com.qst.survey.entity.User
     * @description TODO 更新用户密码
     * @date 2021/4/2
     */
    @Transactional
    @Override
    public User updatePassword(User user) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        int update = userMapper.update(user, queryWrapper);
        return null;
    }

    /**
     * @param email:
     * @return int
     * @description: TODO 发送注册验证码
     * @date 16:40:00 2021/3/20
     */
    @Override
    public int sendEmailCode(String email) {
        AtomicInteger flag = new AtomicInteger();
        String code = GetCode.getSecurityCode();
        String context = "<p style=\" font-size: 18px;\">你好,QoQ投票,你的验证码是(10分钟有效):</p>\n" +
                "   <b style=\"color: #F56C6C; font-size: 30px;\">" + code + "</b>";

        String subject = "QoQ投票";
        redisUtils.setCode(email, code);
        new Thread(() -> {
            mailUtil.sendHtmlMail(email, subject, context);
        }).start();
        return 1;
    }

    /**
     * @param page         ：分页类
     * @param queryWrapper ：Sql查询条件类
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page
     * @description TODO   查出所有的数据
     * @date 2021/4/2
     */
    @Override
    public Page findAll(Page page, QueryWrapper queryWrapper) {
        return userMapper.selectPage(page, queryWrapper);
    }

    /**
     * @param user 用户
     * @return boolean
     * @description TODO  更新一个用户的数据
     * @date 2021/4/2
     */
    @Override
    public User updateUser(User user) {
        int update = userMapper.updateById(user);
        if (update > 0) {
            return userMapper.selectById(user.getId());
        } else {
            return null;
        }
    }

    /**
     * @param id 用户id
     * @return boolean
     * @description TODO 通过id来删除用户
     * @date 2021/4/2
     */
    @Override
    public boolean removeUser(int id) {
        int remove = userMapper.deleteById(id);
        return remove > 0;
    }

    /**
     * @param id ：用户id
     * @return com.qst.survey.entity.User
     * @description TODO  通过用户id来查出一个用户
     * @date 2021/4/2
     */
    @Override
    public User findOneById(int id) {
        return userMapper.selectById(id);
    }

    /**
     * @param id ：用户id
     * @return com.qst.survey.entity.User
     * @description TODO  通过用户id来查出用户回答的投票
     * @date 2021/4/2
     */
    @Override
    public ArrayList<UserReply> findUserReply(int id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", id);
        ArrayList<UserReply> userReplies = (ArrayList<UserReply>) userReplyMapper.selectList(queryWrapper);
        Iterator iterator=userReplies.iterator();
        while(iterator.hasNext()){
            UserReply userReply = (UserReply) iterator.next();
            Question question = questionMapper.selectById(userReply.getQuestionId());
            //判断投票是否已经被删除,被删除就,删掉这条用户回复的记录
            if(question==null){
                iterator.remove();
            }
            userReply.setQuestion(question);
        }

        return userReplies;
    }


    /**
     * 查找age分布字段
     *
     * @return
     */
    @Override
    public List<VM> findAge(Integer id) {
        List<VM> age = userMapper.findAge(id);
        Object obj2 = JSONArray.toJSON(age);
        System.out.println("将List<VM>转成json:" + obj2.toString());
        return age;
    }

    /**
     * 查找分布字段
     *
     * @param id
     * @return
     */
    @Override
    public List<VM> findSex(Integer id) {
        List<VM> sex = userMapper.findSex(id);
        Object obj2 = JSONArray.toJSON(sex);
        System.out.println("将List<VM>转成json:" + obj2.toString());
        return sex;
    }
}
